package com.service.socket.protocol;

public class Packet implements Cloneable {
	// 包头
	private String head = "55";
	//长度低位高位
	public String length;
	// 命令类别
	public String cmdType;
	// 命令字
	public String cmdWord;
	// 状态
	public String status;
	// 设备ID
	public String deviceNo;
	// 数据区
	public String dataArea;
	// crc高位低位
	public String crcValue;
	// 包尾
	private String end = "55";
	
	public String getLength(){
		if (this.dataArea != null && this.dataArea.length()>0)
	    {
	    	return Conversion.intToHexString(16+(this.dataArea.length()/2)).toUpperCase();
	    } else {
	    	return Conversion.intToHexString(16).toUpperCase();
		}
	}
	
	public String getCrcValue(){
		return Conversion.getCrc(head + getLength() + cmdType + cmdWord + status + deviceNo + ((dataArea != null && dataArea.length() > 0)?dataArea:"")).toUpperCase();
	}
	
	public String getDeviceNo() {
		String tmp = deviceNo.replaceFirst("^0+", "");
		if(tmp.equals("")){
			return "00000000000";
		}
		return deviceNo.replaceFirst("^0+", "");
	}

	public void setDeviceNo(String deviceNo) {
		while (deviceNo.length() < 14) {
			deviceNo = "0" + deviceNo;
		}
		this.deviceNo = deviceNo;
	}

	@Override
	public String toString() {
		return head + getLength() + cmdType + cmdWord + status + deviceNo + ((dataArea != null && dataArea.length() > 0)?dataArea:"") + getCrcValue() + end;
	}
	
	public String getRawData() {
		return head + length + cmdType + cmdWord + status + deviceNo + ((dataArea != null && dataArea.length() > 0)?dataArea:"") + crcValue + end;
	}
	
	/**
	 * 验证状态
	 * @return boolean
	 */
	public boolean isCrcValid() {
		return crcValue.equals(this.getCrcValue());
	}
	
	/**
	 * 长度验证
	 * @return
	 */
	public boolean isLenValid(){
		return length.equals(this.getLength());
	}

	/**
	 * 鉴权码
	 * @return
	 */
	public String getAuthCode() {
		String codees = null;
		String[] codes = null;
		String code = null;
		if (dataArea != null && dataArea.trim().length() > 0) {
			codees = Conversion.getStringForCode(dataArea);
		}
		if (codees != null && codees.trim().length() > 0) {
			codes = codees.split(",");
		}
		if (codes != null && codes.length > 0) {
			code = codes[0];
		}
		return code;
	}
	
	@Override  
    public Object clone()
    {  
		try{
			return super.clone();  
		}catch(Exception e){
			return null;
		}
    }
}
